package com.engine4cloud.tdf.supervision.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.engine4cloud.tdf.common.data.web.query.Queries;
import com.engine4cloud.tdf.common.security.service.TdfUser;
import com.engine4cloud.tdf.common.security.util.SecurityUtils;
import com.engine4cloud.tdf.supervision.convert.JzdxCustomFenceConvert;
import com.engine4cloud.tdf.supervision.dto.query.JzdxCustomFenceQueryDTO;
import com.engine4cloud.tdf.supervision.dto.result.JzdxCustomFenceResultDTO;
import com.engine4cloud.tdf.supervision.entity.JzdxCustomFenceEntity;
import com.engine4cloud.tdf.supervision.mapper.JzdxCustomFenceMapper;
import com.engine4cloud.tdf.supervision.service.JzdxCustomFenceService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义电子围栏
 *
 * @author wenjie
 * @date 2024-05-20 10:57:05
 */
@Service
public class JzdxCustomFenceServiceImpl extends ServiceImpl<JzdxCustomFenceMapper, JzdxCustomFenceEntity> implements JzdxCustomFenceService {
    @Override
    public List<JzdxCustomFenceResultDTO> find(JzdxCustomFenceQueryDTO dto) {
        return super.list(wrapper(dto)).stream().map(JzdxCustomFenceConvert.INSTANCE::convert).toList();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateBatch(String code, String batch, List<String> coordinateList) {
        List<JzdxCustomFenceResultDTO> customFenceList = this.find(new JzdxCustomFenceQueryDTO(code, batch));
        if (CollectionUtils.isNotEmpty(customFenceList)) {
            this.removeBatchByIds(customFenceList.stream().map(JzdxCustomFenceResultDTO::getId).toList());
        }

        List<JzdxCustomFenceEntity> customFenceEntityList = new ArrayList<>();
        TdfUser user = SecurityUtils.getUser();
        coordinateList.forEach(coordinate -> customFenceEntityList.add(JzdxCustomFenceConvert.INSTANCE.createCustom(coordinate, code, batch, user.getTenantId())));

        this.saveBatch(customFenceEntityList);
    }

    private LambdaQueryWrapper<JzdxCustomFenceEntity> wrapper(JzdxCustomFenceQueryDTO query) {
        LambdaQueryWrapper<JzdxCustomFenceEntity> wrapper = Queries.lambda();
        Queries.accept(query.getId(), v -> wrapper.eq(JzdxCustomFenceEntity::getId, v));
        Queries.accept(query.getLcbh(), v -> wrapper.eq(JzdxCustomFenceEntity::getLcbh, v));
        Queries.accept(query.getRybh(), v -> wrapper.eq(JzdxCustomFenceEntity::getRybh, v));
        return wrapper;
    }

}